package iss.test;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import pinkblob.entity.DbFile;
import pinkblob.log.Log;
import org.apache.log4j.Logger;

public class DatabaseFileHandler {
	private static EntityManagerFactory emf = null;
	protected static EntityManager em = null;
	
	protected static Logger log = new Log().getLogger(DatabaseFileHandler.class);
		
	public DatabaseFileHandler() {
		if (emf == null) emf = Persistence.createEntityManagerFactory("ISS");
		if (em == null) em = emf.createEntityManager();
		
	}

	public DbFile saveFile(int pid, String filename, long creationDate, byte[] file) throws Exception {
		em.getTransaction().begin();
		DbFile newFile = new DbFile();
		newFile.setProjectInformation(pid);
		newFile.setFilename(filename);
		newFile.setCreatedDate(creationDate);
		newFile.setFile(file);
		newFile.setMailFlag(false);
		
		em.persist(newFile);
		em.getTransaction().commit();
		
		return newFile;
	}
	
	public ArrayList<DbFile> getFiles(int pid) {
		ArrayList<DbFile> result = new ArrayList<DbFile>();
		
		Query q = em.createQuery("SELECT f FROM DbFile f WHERE f.Pid = :pid");
		q.setParameter("pid", pid);
		
		@SuppressWarnings("unchecked")
		List resultList = q.getResultList();
		
		for (Object o : resultList) {
			if (o instanceof DbFile) {
				result.add((DbFile) o);
			} else {
				log.error("this object is not class DbFile");
			}
		}
		
		return result;
	}
	
	// only one file can have the mail flag
	public void setMailFlag(int pid, int fileId){
		ArrayList<DbFile> files = this.getFiles(pid);
		for(DbFile file : files){
			if(file.getId() == fileId)
				file.switchMailFlag();
			else
				file.setMailFlag(false);
		}
	}
	
	public void removeMailFlag(int pid, int fileId){
		DbFile file = getMailFlagFile(pid);
		file.setMailFlag(false);
	}
	
	public void removeAllMailFlags(int pid) {
		ArrayList<DbFile> files = this.getFiles(pid);
		for(DbFile file : files){			
				file.setMailFlag(false);
		}
	}
	
	public DbFile getMailFlagFile(int pid){
		ArrayList<DbFile> files = this.getFiles(pid);
		DbFile outputfile = null;
			for(DbFile file : files){
				if (file.getMailFlag()) outputfile = file;
			}
		return outputfile;
	}
}
